<script setup>
import { reactive, ref, watch, onMounted } from "vue";
import { useRouter } from "vue-router"
import request from '@/api/request'
import { Delete, Edit, Search, Plus, Refresh } from '@element-plus/icons-vue'
// 新增：导入ElMessage用于提示
import { ElMessage, ElMessageBox } from 'element-plus'

let router = useRouter();
const rules = reactive({})

let columns = [
    { id: "unitId", label: "单位编码" },
    { id: "unitName", label: "单位名称" },
    { id: "isMainUnit", label: "是否为主单位" },
    { id: "conversionRate", label: "与主单位转换率" },
    { id: "status", label: "是否启用" },
   
]

let isdisabled = ref(true) // 顶部修改按钮禁用状态
let isdisabledreove = ref(true) // 顶部删除按钮禁用状态
let isVisible = ref(false) // 对话框显示状态
let data = ref({}) // 用于传递给修改表单的数据
let title = ref("") // 对话框标题

// 新增：保存选中的完整行数据（用于修改）
let selectedRows = ref([])
// 选中项的ID数组（用于批量操作）
let shipment_history_id = ref([])

let page = ref({
    current: 1,
    size: 5,
    total: 0,
    records: []
})

let unitConversion = ref({
    unitId: '',
    unitName: ''
})

// 搜索
const handleSearch = () => {
    page.value.current = 1;
    loadData();
}

// 加载表格数据
let loadData = () => {
    request({
        url: '/unitConversion/index',
        method: 'get',
        params: {
            current: page.value.current,
            size: page.value.size,
            unitId: unitConversion.value.unitId,
            unitName: unitConversion.value.unitName
        }
    }).then(res => {
        page.value = res.data
    }).catch(err => {
        ElMessage.error('数据加载失败')
    })
}

loadData();

// 刷新表格
let refTanle = () => {
    isVisible.value = false;
    loadData();
}

// 跳转到新增页面
let toInsert = () => {
    title.value = "新增单位";
    isVisible.value = true;
    router.push("/material/unit/insert");
}

// 修改操作（接收行数据）
let toUpdate = async(row) => {
    data.value = { ...row }; // 深拷贝选中行数据，避免直接修改原数据
    title.value = "修改单位";
    isVisible.value = true;
    router.push("/material/unit/update");
}

// 单条删除
let toRemove = (unitId) => {
    ElMessageBox.confirm('确定要删除这条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        request({
            url: "/unitConversion/delete",
            method: "delete",
            data: unitId
        }).then(res => {
            ElMessage.success('删除成功')
            loadData()
        }).catch(err => {
            ElMessage.error('删除失败')
        })
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}

// 表格选择事件：更新选中状态和按钮禁用状态
let fuxuankuang = (selected) => {
    selectedRows.value = selected; // 保存选中的完整行数据
    shipment_history_id.value = selected.map(b => b.id); // 提取选中项ID
    
    // 根据选中数量更新按钮状态
    if (selected.length === 1) {
        isdisabled.value = false; // 选中1条，启用修改按钮
        isdisabledreove.value = false; // 启用删除按钮
    } else if (selected.length > 1) {
        isdisabled.value = true; // 选中多条，禁用修改按钮
        isdisabledreove.value = false; // 启用删除按钮
    } else {
        isdisabled.value = true; // 未选中，禁用修改按钮
        isdisabledreove.value = true; // 禁用删除按钮
    }
}



const defaultProps = {
    children: 'children',
    label: 'label',
}

const filterText = ref('')
const treeRef = ref()

const expandAllNodes = () => {
    const tree = treeRef.value
    if (tree) {
        const allNodes = tree.store._getAllNodes()
        allNodes.forEach(node => {
            node.expanded = true
        })
    }
}

onMounted(() => {
    expandAllNodes()
})

const filterNode = (value, data, node) => {
    if (!value) return true
    if (data.label.includes(value)) {
        expandParentsAndSiblings(node)
        return true
    }
    return isParentOrSiblingOfMatch(node, value)
}

const expandParentsAndSiblings = (node) => {
    let parent = node.parent
    while (parent) {
        parent.expanded = true
        parent = parent.parent
    }
    if (node.parent) {
        node.parent.childNodes.forEach(child => {
            child.expanded = true
        })
    }
}

const isParentOrSiblingOfMatch = (node, value) => {
    if (node.childNodes) {
        for (const child of node.childNodes) {
            if (child.data?.label.includes(value)) {
                return true
            }
        }
    }
    if (node.parent) {
        for (const sibling of node.parent.childNodes) {
            if (sibling.data?.label.includes(value)) {
                return true
            }
        }
    }
    return false
}

watch(filterText, (val) => {
    treeRef.value.filter(val)
    if (val) {
        const tree = treeRef.value
        const allNodes = tree.store._getAllNodes()
        allNodes.forEach(node => {
            node.expanded = false
        })
        allNodes.forEach(node => {
            if (node.data?.label.includes(val)) {
                expandParentsAndSiblings(node)
            }
        })
    } else {
        expandAllNodes()
    }
})

let formRef = ref()

// 重置
let chongzhi = () => {
    unitConversion.value = {
        unitId: '',
        unitName: ''
    }
    filterText.value = ''
    expandAllNodes()
    handleSearch()
}

const formData = ref({
    unitName: '',
})

// 新增成功后的回调
const handleAddSuccess = (newUnit) => {
    page.value.records.unshift({
        id: Date.now(),
        unitId: newUnit.unitId,
        unitName: newUnit.unitName,
        isMainUnit: newUnit.isMainUnit,
        conversionRate: newUnit.conversionRate,
        status: newUnit.status 
    })
    page.value.total += 1
    isVisible.value = false
    ElMessage.success('新增成功')
}

// 新增：顶部修改按钮点击事件（使用选中的行数据）
const handleTopUpdate = () => {
    if (selectedRows.value.length === 1) {
        toUpdate(selectedRows.value[0]) // 传递选中的行数据给修改方法
    }
}

// 新增：顶部删除按钮批量删除功能
const handleTopRemove = () => {
    ElMessageBox.confirm(`确定要删除选中的${shipment_history_id.value.length}条数据吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        request({
            url: "/material/batchDelete", // 假设后端有批量删除接口
            method: "delete",
            data: shipment_history_id.value // 传递ID数组
        }).then(res => {
            ElMessage.success('批量删除成功')
            loadData()
        }).catch(err => {
            ElMessage.error('批量删除失败')
        })
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}
</script>

<template>
    <div>
        <el-card>
            <template #header>
                <div>
                    <el-row>
                        

                        <el-col :span="24">
                            <el-form ref="formRef" inline :model="unitConversion"
                                style="display: flex;justify-content: start;" class="card_wrap">
                                <el-form-item label="单位编码" size="default" prop="unitId" class="c_item">
                                    <el-input v-model="unitConversion.unitId" class="sousuo"
                                        placeholder="请输入单位编码" clearable @change="handleSearch"></el-input>
                                </el-form-item>
                                <el-form-item label="单位名称" size="default" prop="unitName" class="c_item">
                                    <el-input v-model="unitConversion.unitName" class="sousuo"
                                        placeholder="请输入单位名称" clearable @change="handleSearch"></el-input>
                                </el-form-item>
                                <el-form-item class="c_item">
                                    <template #default>
                                        <el-button type="primary" size="default" @click="handleSearch" :icon="Search">搜索</el-button>
                                        <el-button type="info" size="default" :plain=true @click="chongzhi" :icon="Refresh">重置</el-button>
                                    </template>
                                </el-form-item>
                            </el-form>

                            <div style="margin-top: 20px;">
                                <el-button @click="toInsert" type="primary" :plain="true" :icon="Plus">添加</el-button>
                                <!-- 修改：顶部修改按钮绑定新的点击事件handleTopUpdate -->
                                <el-button type="success" size="default" :plain=true @click="handleTopUpdate" :icon="Edit" 
                                    style="border:0px" :disabled="isdisabled">修改</el-button>
                                <!-- 修改：顶部删除按钮绑定批量删除事件handleTopRemove -->
                                <el-button type="danger" size="default" :plain=true @click="handleTopRemove" :icon="Delete" 
                                    style="border:0px" :disabled="isdisabledreove">删除</el-button>
                            </div>

                            <el-table :data="page.records" border stripe @selection-change="fuxuankuang">
                                <el-table-column type="selection" width="55" />
                                <el-table-column prop="unitId" label="单位编码"/>
                                <el-table-column prop="unitName" label="单位名称"/>
                                <el-table-column prop="isMainUnit" label="是否为主单位"  #default="scope">
                                    <el-tag :type="scope.row.isMainUnit=='1' ? 'primary':'danger'">{{ scope.row.isMainUnit=="1" ? "是" :"否"}}</el-tag>
                                </el-table-column>
                                <el-table-column  prop="conversionRate" label="与主单位转换率" />
                                <el-table-column prop="status" label="是否启用" #default="scope">
                                    <el-tag :type="scope.row.status=='1' ? 'primary':'danger'">{{ scope.row.status=="1"?"是":"否"}}</el-tag>
                                </el-table-column>
                                <el-table-column label="操作" fixed="right" >
                                    <template #default="scope">
                                        <el-button size="small" type="primary" @click="toUpdate(scope.row)" :icon="Edit">修改</el-button>
                                        <el-button size="small" type="danger" @click="toRemove(scope.row.materialId)" :icon="Delete">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-pagination @current-change="(val) => { page.current = val; loadData() }" 
                                v-model:currentPage="page.current"
                                :page-sizes="[2, 4, 6, 8, 10]" :page-size="page.size" :total="page.total" background>
                            </el-pagination>
                        </el-col>
                    </el-row>
                    <div style="width:800px">
                        <el-dialog :title="title" v-model="isVisible" :destroy-on-close="true" width="60%">
                            <router-view @ref-table="refTanle" :data="data">
                            </router-view>
                        </el-dialog>
                    </div>
                </div>
            </template>
        </el-card>
    </div>
</template>

<style scoped>
.sousuo {
    width: 200px;
}

.card_wrap {
    width: 98%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
}

.c_item {
    flex: 1;
    margin: 0px 5px 15px 0;
    width: calc((100%-10px)/3);
    min-width: calc((100% - 10px)/3);
    max-width: calc((100% - 10px)/3);

    &:nth-child(3n) {
        margin-right: 0;
    }
}

.filter-tree :deep(.el-tree-node__content) {
    height: auto;
    padding: 5px 0;
}
</style>